package com.szmmsoft.mp.common.config;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.redisson.config.TransportMode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * Description of the class.
 *
 * @author ethan
 * @version 1.0.0
 * @since 2024-10-11
 */
@Configuration
@Slf4j
public class RedisConfig {
    @Value("${spring.data.redis.url}")
    private String url;
    @Value("${spring.data.redis.database}")
    private Integer database;
    @Value("${spring.data.redis.password}")
    private String password;
    @Value("${spring.data.redis.port}")
    private String port;

    @Bean(destroyMethod = "shutdown")
    RedissonClient singleRedisson() throws IOException {
        Config config = new Config();
        config.setCodec(StringCodec.INSTANCE);
        if (!StrUtil.isEmpty(password)) {
            config.useSingleServer().setPassword(password);
        }
        config.useSingleServer().setAddress(String.format("redis://%s:%s", url, port));
        config.useSingleServer().setDatabase(database);
        config.setTransportMode(TransportMode.NIO);
        return Redisson.create(config);
    }
}
